package 打牢基础30天.day01.my;

import 打牢基础30天.util.ArrUtil;

/**
 * @Author yaya
 * @Create 2024/6/4 15:19
 * Description:冒泡排序
 */
public class Code02_BubbleSort {

    public static void bubbleSort(int[] arr) {
        if (arr == null || arr.length < 2) return;

        // 范围从大到小
        for (int i = arr.length - 1; i > 0; i--) {
            // 如果是大的值，不断的替换到后面
            for (int j = 0; j < i; j++) {
                if (arr[j] > arr[j + 1]) {
                    swap(arr, j, j + 1);
                }
            }
        }
    }

    public static void swap(int[] arr, int i, int j) {
        if (i == j || arr[i] == arr[j]) return;

        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    public static void bubbleSort2(int[] arr) {
        if (arr == null || arr.length < 2) return;
        for (int i = arr.length - 1; i >= 0; i--) {
            for (int j = 0; j < i; j++) {
                if (arr[j] > arr[j + 1]) {
                    swap(arr, j, j + 1);
                }
            }
        }
    }

    // test
    public static void main(String[] args) {
        int testTime = 500000;
        int maxSize = 100;
        int maxValue = 100;
        boolean succeed = true;
        for (int i = 0; i < testTime; i++) {
            int[] arr1 = ArrUtil.generateRandomArray(maxSize, maxValue);
            int[] arr2 = ArrUtil.copyArray(arr1);
            bubbleSort2(arr1);
            ArrUtil.comparator(arr2);
            if (!ArrUtil.isEqual(arr1, arr2)) {
                succeed = false;
                ArrUtil.printArray(arr1);
                ArrUtil.printArray(arr2);
                break;
            }
        }
        System.out.println(succeed ? "Nice!" : "花Q!");
    }
}
